/*
 * @Date: 2019-12-2
 * @Author: xuechengwu <xuechengwu@erayt.com>
 * @Description: MACD 技术指标层
 */
import Layer from '../core/Layer';
import Point from '../core/Point';
import MultiLine from '../base/MultiLine';
import Rectangle from '../base/Rectangle';
import Color from '../core/Color';

export default class MACDLayer extends Layer {
  constructor(canvas, option) {
    super(canvas);
    this.width = option.width;
    this.height = option.height;
    this.xStep = option.xStep;
    this.data = option.data;
    this.barRed = option.barRed || '#F75A5A';
    this.barGreen = option.barGreen || '#008737';
    this.difColor = option.difColor || '#FF0000';
    this.deaColor = option.deaColor || '#3393B8';
  }

  /**
   * 渲染
   */
  make() {
    if (this.data.DIF.length === 0) {
      return;
    }
    this.childs.splice(0, this.childs.length);
    let maxOfBar = -10000000000;
    let maxOfValue = -1000000000;
    for (let i = 0; i < this.data.DIF.length; i++) {
      if (Math.abs(this.data.DIF[i]) > maxOfValue) {
        maxOfValue = Math.abs(this.data.DIF[i]);
      }
      if (Math.abs(this.data.DEA[i]) > maxOfValue) {
        maxOfValue = Math.abs(this.data.DEA[i]);
      }
      if (Math.abs(this.data.BAR[i]) > maxOfBar) {
        maxOfBar = Math.abs(this.data.BAR[i]);
      }
    }
    const stepOfBar = this.height / maxOfBar / 2;
    const stepOfValue = this.height / maxOfValue / 2;
    const DIFPoint = [];
    const DEAPoint = [];
    for (let i = 0; i < this.data.DIF.length; i++) {
      DIFPoint.push(new Point(this.position.x + i * this.xStep, this.position.y + (this.data.DIF[i] + maxOfValue) * stepOfValue));
      DEAPoint.push(new Point(this.position.x + i * this.xStep, this.position.y + (this.data.DEA[i] + maxOfValue) * stepOfValue));
      if (this.data.BAR[i] > 0) {
        const barHeight = stepOfBar * this.data.BAR[i];
        const rect = new Rectangle(this.canvas, {
          width: this.xStep * 0.2,
          height: barHeight,
          color: this.barRed
        });
        rect.setPosition((i + 0.4) * this.xStep, this.height / 2);
        this.addChild(rect);
      } else {
        const barHeight = stepOfBar * Math.abs(this.data.BAR[i]);
        const rect = new Rectangle(this.canvas, {
          width: this.xStep * 0.2,
          height: barHeight,
          color: this.barGreen
        });
        rect.setPosition((i + 0.4) * this.xStep, this.height / 2 - barHeight);
        this.addChild(rect);
      }
    }
    const DIFLine = new MultiLine(this.canvas, DIFPoint);
    const DEALine = new MultiLine(this.canvas, DEAPoint);
    DIFLine.setColor(new Color(this.difColor));
    DEALine.setColor(new Color(this.deaColor));
    this.addChild(DIFLine, DEALine);
  }
}
